package com.postpeakliving.store.client;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

public class ShopCart {
	private List<String> addToCartUrlList;

	public void setAddToCartUrl(List<String> urls) {
		this.addToCartUrlList = urls;
	}

	public List<String> getaddToCartUrl() {
		return this.addToCartUrlList;
	}

	public static ShopCart jsonToJava(JSONValue jsonValue) {
		JSONArray jsonArray = jsonValue.isArray();
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < jsonArray.size(); i++) {
			String url = new String();
			url = jsonArray.get(i).toString();
			int beginIndex = url.indexOf("\"");
			int endIndex = url.lastIndexOf("\"");
			url = url.substring(beginIndex + 1, endIndex);
			list.add(url);
		}
		ShopCart shopCart = new ShopCart();
		shopCart.setAddToCartUrl(list);
		return shopCart;
	}

	public String getJSONString() {
		String jsonString = "[";
		List<String> list = this.getaddToCartUrl();
		int size = list.size();
		for (int i = 0; i < size; i++) {
			if (i == size - 1) {
				jsonString += "\"" + list.get(i) + "\"";
			} else {
				jsonString += "\"" + list.get(i) + "\",";
			}
		}
		jsonString += "]";
		return jsonString;
	}

	public static JSONValue javaToJson(ShopCart shopCart) {
		return JSONParser.parse(shopCart.getJSONString());
	}

	public String pop() {
		String url = new String();
		Iterator<String> it = addToCartUrlList.iterator();
		if (it.hasNext()) {
			url = it.next();
			it.remove();
		}
		return url;
	}

	public boolean isEmpty() {
		if (this.addToCartUrlList.size() > 0) {
			return false;
		} else {
			return true;
		}
	}
	
	public int getItemCount(){
		return this.addToCartUrlList.size();
	}
}
